package com.ph.interceptor;

import java.util.Map;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.ph.irp.base.log.action.LogAction;
import com.ph.irp.base.log.service.LogService;
import com.ph.irp.base.usermanage.action.UserManageAction;
import com.ph.irp.login.action.LoginAction;
import com.ph.irp.model.PBaseLog;
import com.ph.util.DateUtil;
import com.ph.util.PropertiesUtil;

public class LoggerInterceptor extends AbstractInterceptor  {
	// 1为开始，2为完成，3为取消，4为失败。缺省为0，无意义
	private static final int STATE_START = 1;
	private static final int STATE_END = 2;
	private static final int STATE_CANCEL = 3;
	private static final int STATE_FAIL = 4;
	
	private LogService logService;

	public LogService getLogService() {
		return logService;
	}

	public void setLogService(LogService logService) {
		this.logService = logService;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String intercept(ActionInvocation actionExecute) throws Exception {
		Object action = actionExecute.getAction();
		String actionName = actionExecute.getProxy().getActionName();

		if (!actionName.equals("index") && !(action instanceof LogAction)
				&& !(action instanceof UserManageAction)
				&& !(action instanceof LoginAction)) {
			addLog(actionExecute);
			actionExecute.invoke();
			addLog(actionExecute);
		} else {
			actionExecute.invoke();
		}

		return Action.SUCCESS;
	}

	private void addLog(ActionInvocation actionExecute) {
		try {
			String methodName = actionExecute.getProxy().getMethod();

			if (methodName != null && !methodName.equals("")
					&& PropertiesUtil.isExisted(methodName)) {
				Map session = actionExecute.getInvocationContext().getSession();
				String resultCode = actionExecute.getResultCode();
				PBaseLog log = new PBaseLog();
				log.setFunctionId(Integer.parseInt(PropertiesUtil
						.getPropertyValue(methodName)));
				log.setHappenTime(DateUtil.date2Timestamp(DateUtil
						.getCurrentDateTime()));

				if (resultCode != null) {
					if (resultCode.equals("input")
							|| resultCode.equals("exception")) {
						log.setState(STATE_FAIL);
					} else {
						log.setState(STATE_END);
					}
				} else {
					log.setState(STATE_START);
				}

				log.setUserId(session.isEmpty() ? 0 : (Integer) session
						.get("userId"));

				logService.addLog(log);
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
}
